<script lang="ts" setup name="XtxCity">
import useStore from '@/store'
import { ref, watch } from 'vue'
import { onClickOutside } from '@vueuse/core'
import { AreaList } from '@/types/data'
import { CitySelect } from '@/types/data'
// 接收显示完整城市数据
defineProps({
  fullAdrees: {
    type: String
  }
})
const emits = defineEmits<{
  (e: 'getResult', obj: CitySelect): void
}>()
const { goods } = useStore()
// 调用获取城市数据方法，获取城市数据
goods.getCityList()
// 定义用于控制城市选择窗口显示与隐藏
const isShow = ref(false)
const target = ref(null)
// 当鼠标点击界面其他地方时，关闭城市选择弹层
onClickOutside(target, () => {
  isShow.value = false
})

// 选择城市
const changeResult = ref({
  provinceCode: '',
  provinceName: '',
  cityCode: '',
  cityName: '',
  countyCode: '',
  countyName: ''
})

// 点击城市选择点击事件
const cityClick = (i: AreaList) => {
  if (i.level === 0) {
    goods.setCityList(i.areaList)
    changeResult.value.provinceName = i.name
    changeResult.value.provinceCode = i.code
  } else if (i.level === 1) {
    goods.setCityList(i.areaList)
    changeResult.value.cityName = i.name
    changeResult.value.cityCode = i.code
  } else {
    changeResult.value.countyName = i.name
    changeResult.value.countyCode = i.code
    isShow.value = false
    emits('getResult', changeResult.value)
  }
}

const stop = watch(isShow, newVal => {
  if (!newVal) {
    goods.setInitCityList()
  }
})
</script>

<script lang="ts">
export default {
  name: 'XtxCity'
}
</script>
<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="isShow = !isShow">
      <span class="placeholder">{{ fullAdrees }}</span>
      <span class="value"></span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-show="isShow">
      <span
        class="ellipsis"
        @click="cityClick(i)"
        v-for="i in goods.cityList"
        :key="i.code"
        >{{ i.name }}</span
      >
    </div>
  </div>
</template>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
